package org.marsdonne.auth;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

import javax.annotation.Resource;
import java.util.List;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
import static org.springframework.core.Ordered.LOWEST_PRECEDENCE;

@Configuration
@EnableWebSecurity
public class ResourceServerConfigurer extends WebSecurityConfigurerAdapter {

    @Configuration
    @ConfigurationProperties("auth.authentication")
    public static class PermitConfigurer {
        private List<String> permitPatterns;

        public List<String> getPermitPatterns() {
            return permitPatterns;
        }

        public void setPermitPatterns(List<String> permitPatterns) {
            this.permitPatterns = permitPatterns;
        }
    }

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    private String jwkSetUri;

    @Resource
    private PermitConfigurer permitConfigurer;

    @Bean
    @ConditionalOnMissingBean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests((requests) -> {
                    if (permitConfigurer.permitPatterns != null)
                        for (String pattern : permitConfigurer.permitPatterns) {
                            requests.antMatchers(pattern).permitAll();
                        }

                    requests.anyRequest().authenticated();
                }
        ).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}

